ngx.req.read_body()  -- 读取请求体
local auth_header = ngx.req.get_headers()["Authorization"] or ""

if not auth_header:find("Basic ") then
    ngx.header.content_type = "text/plain"
    ngx.status = ngx.HTTP_UNAUTHORIZED
    ngx.header.www_authenticate = 'Basic realm="Restricted"'
    ngx.say("401 Unauthorized: No authorization header")
    ngx.exit(ngx.HTTP_UNAUTHORIZED)
end

local encoded_cred = auth_header:sub(7)
local decoded_cred = ngx.decode_base64(encoded_cred)
if not decoded_cred then
    ngx.header.content_type = "text/plain"
    ngx.status = ngx.HTTP_UNAUTHORIZED
    ngx.header.www_authenticate = 'Basic realm="Restricted"'
    ngx.say("401 Unauthorized: Invalid Base64 encoding")
    ngx.exit(ngx.HTTP_UNAUTHORIZED)
end

local user, pass = decoded_cred:match("([^:]+):([^:]+)")

-- 这里替换为您自己的验证逻辑
if user ~= "admin" or pass ~= "password" then
    ngx.header.content_type = "text/plain"
    ngx.status = ngx.HTTP_UNAUTHORIZED
    ngx.header.www_authenticate = 'Basic realm="Restricted"'
    ngx.say("401 Unauthorized: Incorrect credentials")
    ngx.exit(ngx.HTTP_UNAUTHORIZED)
else
    -- 用户验证成功，返回用户名、密码和当前服务器时间
    local current_time = os.date("%Y-%m-%d %H:%M:%S")
    ngx.header.content_type = "text/plain"
    ngx.say("Login successful!")
    ngx.say("Username: " .. user)
    ngx.say("Password: " .. pass)
    ngx.say("Current Server Time: " .. current_time)
end
